import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "~/components/ui/dialog";
import { Input } from "~/components/ui/input";
import { Button } from '~/components/ui/button';
import { authActions } from '~/core/store';

interface LoginDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onLoginSuccess: (username: string) => void;
  onNavigateToRegister: () => void;
}

interface CaptchaResponse {
  captcha_id: string;
  image_data: string;
}

export function LoginDialog({ 
  open, 
  onOpenChange, 
  onLoginSuccess,
  onNavigateToRegister
}: LoginDialogProps): React.JSX.Element {
  const [formData, setFormData] = useState({ 
    username: '', 
    password: '',
    captcha: '' 
  });
  const [captchaId, setCaptchaId] = useState('');
  const [captchaImage, setCaptchaImage] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  // 当对话框打开时获取验证码
  useEffect(() => {
    if (open) {
      fetchCaptcha();
    }
  }, [open]);

  const fetchCaptcha = async () => {
    try {
      setError('');
      const response = await fetch('/api/captcha', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
      });

      if (!response.ok) {
        throw new Error('获取验证码失败');
      }

      const data: CaptchaResponse = await response.json();
      setCaptchaId(data.captcha_id);
      setCaptchaImage(data.image_data);
    } catch (err) {
      setError('无法加载验证码，请重试');
      console.error('Fetch captcha error:', err);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      // 构建登录请求体
      const loginRequest = {
        username: formData.username,
        password: formData.password,
        captcha_id: captchaId,
        captcha_code: formData.captcha
      };

      const response = await fetch('/api/token', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(loginRequest),
      });

      if (!response.ok) {
        // 验证码错误时刷新验证码
        if (response.status === 400) {
          const errorData = await response.json();
          if (errorData.detail === 'Invalid captcha') {
            fetchCaptcha(); // 刷新验证码
            setFormData(prev => ({ ...prev, captcha: '' })); // 清空验证码输入框
          }
        }
        
        // 处理其他错误
        const errorData = await response.json();
        throw new Error(errorData.detail || '登录失败');
      }

      // 处理成功登录
      const { access_token } = await response.json();
      authActions.login(formData.username, access_token);
      localStorage.setItem('access_token', access_token);
      onLoginSuccess(formData.username);
      onOpenChange(false);
      setFormData({ username: '', password: '', captcha: '' });
    } catch (err) {
      let errorMessage = '登录失败，请稍后重试';
      if (err instanceof Error) errorMessage = err.message;
      setError(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { id, value } = e.target;
    setFormData(prev => ({ ...prev, [id]: value }));
  };

  return (
    <Dialog 
      open={open} 
      onOpenChange={onOpenChange}
      className="flex items-center justify-center bg-black/50"
    >
      <DialogContent className="sm:max-w-[425px] mt-[-20px] sm:mt-0">
        <DialogHeader>
          <DialogTitle className="text-lg">用户登录</DialogTitle>
        </DialogHeader>
        
        {error && (
          <div className="bg-red-50 text-red-700 px-4 py-2 rounded text-sm">
            {error}
          </div>
        )}
        
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid gap-2">
            <label htmlFor="username" className="text-sm font-medium">
              用户名
            </label>
            <Input
              id="username"
              value={formData.username}
              onChange={handleChange}
              placeholder="请输入用户名"
              required
            />
          </div>
          
          <div className="grid gap-2">
            <label htmlFor="password" className="text-sm font-medium">
              密码
            </label>
            <Input
              id="password"
              type="password"
              value={formData.password}
              onChange={handleChange}
              placeholder="请输入密码"
              required
            />
          </div>
          
          <div className="grid grid-cols-[1fr_auto] gap-4">
            <div>
              <label htmlFor="captcha" className="text-sm font-medium">
                验证码
              </label>
              <Input
                id="captcha"
                value={formData.captcha}
                onChange={handleChange}
                placeholder="请输入验证码"
                className="mt-1"
                required
              />
            </div>
            
            <div className="pt-5">
              {captchaImage ? (
                <div 
                  className="border rounded cursor-pointer h-10 w-32"
                  onClick={fetchCaptcha}
                  title="点击刷新验证码"
                >
                  <img 
                    src={captchaImage} 
                    alt="验证码" 
                    className="w-full h-full object-cover"
                  />
                </div>
              ) : (
                <div className="bg-gray-200 border-2 border-dashed rounded-xl w-32 h-10 flex items-center justify-center">
                  <span className="text-gray-500 text-xs">加载中...</span>
                </div>
              )}
            </div>
          </div>
          
          <div className="flex items-center justify-end space-x-2 pt-2">
            <span className="text-sm text-muted-foreground">新用户？</span>
            <Button
              variant="link"
              type="button"
              className="h-auto p-0 text-primary/80 hover:text-primary"
              onClick={onNavigateToRegister}
            >
              立即注册
            </Button>
          </div>
          
          <Button 
            variant="default"
            size="sm"
            type="submit"
            className="w-full mt-2 font-medium"
            disabled={loading}
          >
            {loading ? '登录中...' : '立即登录'}
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}